package com.agh.portal.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.agh.portal.domain.Question;
import com.agh.portal.service.DataService;
import com.agh.portal.service.SecurityUtils;

@RequestMapping("/questions")
@Controller
@RooWebScaffold(path = "questions", formBackingObject = Question.class)
@RooWebFinder
public class QuestionController {
	
	@Autowired
	SecurityUtils secUtils;
	
	//TODO: @Secured("logged user")
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Question question, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {

        if (bindingResult.hasErrors()) {
        	System.out.println(bindingResult.getFieldErrors());
            populateEditForm(uiModel, question);
            return "questions/create";
        }
        uiModel.asMap().clear();
        question.setCreationDate(new Date());
        question.setStudent(secUtils.getLoggedStudent());
        question.persist();
        return "redirect:/questions/" + encodeUrlPathSegment(question.getId().toString(), httpServletRequest);
    }
	
    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        Question q = Question.findQuestion(id);
        uiModel.addAttribute("question", q);
        uiModel.addAttribute("answers", DataService.sortAnswersByDate(q.getAnswers()));
        uiModel.addAttribute("itemId", id);
        return "questions/show";
    }
    
    
}
